package droidninja.filepicker.utils;

import android.content.ContentResolver;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;

import droidninja.filepicker.FilePickerConst;
import droidninja.filepicker.R;

/**
 * Created by droidNinja on 08/03/17.
 */

public class FileUtils {

    public static int getTypeDrawable(String path) {
        if (getFileType(path) == FilePickerConst.FILE_TYPE.EXCEL)
            return R.drawable.ic_excel;
        if (getFileType(path) == FilePickerConst.FILE_TYPE.WORD)
            return R.drawable.ic_word;
        if (getFileType(path) == FilePickerConst.FILE_TYPE.PPT)
            return R.drawable.ic_ppt;
        if (getFileType(path) == FilePickerConst.FILE_TYPE.PDF)
            return R.drawable.ic_pdf;
        if (getFileType(path) == FilePickerConst.FILE_TYPE.TXT)
            return R.drawable.ic_txt;
        else
            return R.drawable.ic_txt;
    }

    public static FilePickerConst.FILE_TYPE getFileType(String path) {
        String fileExtension = FilePickerUtils.getFileExtension(new File(path));
        if (TextUtils.isEmpty(fileExtension))
            return FilePickerConst.FILE_TYPE.UNKNOWN;

        if (isExcelFile(path))
            return FilePickerConst.FILE_TYPE.EXCEL;
        if (isDocFile(path))
            return FilePickerConst.FILE_TYPE.WORD;
        if (isPPTFile(path))
            return FilePickerConst.FILE_TYPE.PPT;
        if (isPDFFile(path))
            return FilePickerConst.FILE_TYPE.PDF;
        if (isTxtFile(path))
            return FilePickerConst.FILE_TYPE.TXT;
        else
            return FilePickerConst.FILE_TYPE.UNKNOWN;
    }

    public static boolean isExcelFile(String path) {
        String[] types = {"xls", "xlsx"};
        return FilePickerUtils.contains(types, path);
    }

    public static boolean isDocFile(String path) {
        String[] types = {"doc", "docx", "dot", "dotx"};
        return FilePickerUtils.contains(types, path);
    }

    public static boolean isPPTFile(String path) {
        String[] types = {"ppt", "pptx"};
        return FilePickerUtils.contains(types, path);
    }

    public static boolean isPDFFile(String path) {
        String[] types = {"pdf"};
        return FilePickerUtils.contains(types, path);
    }

    public static boolean isTxtFile(String path) {
        String[] types = {"txt"};
        return FilePickerUtils.contains(types, path);
    }

    public static boolean isImageFile(String path) {
        String[] types = {"png", "jpg", "jpeg", "gif", "bmp",};
        return FilePickerUtils.contains(types, path);
    }
    public static boolean isAudioFile(String path) {
        String[] types = {"mp3", "wav", "aac", "amr"};
        return FilePickerUtils.contains(types, path);
    }
    public static boolean isVideoFile(String path) {
        String[] types = {"mp4", "avi", "mpeg", "flv", "3gp", "mov"};
        return FilePickerUtils.contains(types, path);
    }

    public static long fileSize(String file) {
        return fileSize(new File(file));
    }

    public static long fileSize(File file) {
        long length = file.length();
        if (length != 0) {
            return length;
        }
        FileChannel channel = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(file);
            channel = fileInputStream.getChannel();
            return channel.size();
        } catch (IOException ignored) {
            return 0;
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException ignored) {

                }
            }
            if (channel != null) {
                try {
                    channel.close();
                } catch (IOException ignored) {

                }
            }
        }
    }

    public static String formatFileSize(long size) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (size == 0) {
            return wrongSize;
        }
        if (size < 1024) {
            fileSizeString = df.format((double) size) + "B";
        } else if (size < 1048576) {
            fileSizeString = df.format((double) size / 1024) + "KB";
        } else if (size < 1073741824) {
            fileSizeString = df.format((double) size / 1024) + "MB";
        } else if (size < 1099511627776L) {
            fileSizeString = df.format((double) size / 1073741824) + "GB";
        } else if (size < 1125899906842624L) {
            fileSizeString = df.format((double) size / 1099511627776L) + "TB";
        } else {
            fileSizeString = df.format((double) size / 1125899906842624L) + "PB";
        }
        return fileSizeString;
    }

    public static String formatFileSize(String file) {
        return formatFileSize(fileSize(file));
    }

    public static String formatFileSize(File file) {
        return formatFileSize(fileSize(file));
    }


    /**
     * Return whether the file exists.
     *
     * @param file The file.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isFileExists(final Context context, final File file) {
        if (file == null) return false;
        if (file.exists()) {
            return true;
        }
        return isFileExists(context, file.getAbsolutePath());
    }

    /**
     * Return whether the file exists.
     *
     * @param filePath The path of file.
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isFileExists(final Context context, final String filePath) {
        if (filePath == null || TextUtils.isEmpty(filePath)) {
            // 地址不存在
            return false;
        }
        File file = new File(filePath);
        if (file.exists()) {
            return true;
        }
        return isFileExistsApi29(context, filePath);
    }

    private static boolean isFileExistsApi29(final Context context, String filePath) {
        if (Build.VERSION.SDK_INT >= 29) {
            try {
                Uri uri = Uri.parse(filePath);
                ContentResolver cr = context.getApplicationContext().getContentResolver();
                AssetFileDescriptor afd = cr.openAssetFileDescriptor(uri, "r");
                if (afd == null) return false;
                try {
                    afd.close();
                } catch (IOException ignore) {
                }
            } catch (FileNotFoundException e) {
                return false;
            }
            return true;
        }
        return false;
    }
}
